package com.wux.labs.spring.springbucks.handler

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 金额类型的数据转换
 */
class MoneyTypeHandler : BaseTypeHandler<Money>() {
    @Throws(SQLException::class)
    override fun setNonNullParameter(ps: PreparedStatement, i: Int, parameter: Money, jdbcType: JdbcType?) {
        ps.setLong(i, parameter.amountMinorLong)
    }

    @Throws(SQLException::class)
    override fun getNullableResult(rs: ResultSet, columnName: String): Money {
        return parseMoney(rs.getLong(columnName))
    }

    @Throws(SQLException::class)
    override fun getNullableResult(rs: ResultSet, columnIndex: Int): Money {
        return parseMoney(rs.getLong(columnIndex))
    }

    @Throws(SQLException::class)
    override fun getNullableResult(cs: CallableStatement, columnIndex: Int): Money {
        return parseMoney(cs.getLong(columnIndex))
    }

    private fun parseMoney(value: Long): Money {
        return Money.of(CurrencyUnit.of("CNY"), value / 100.0)
    }
}
